<template>
  <div class="account-box">
    <div class="toggle">
      <a @click="loginType()" href="javascript:;" v-if="isMsgLogin">
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
      <a @click="loginType()" href="javascript:;" v-else>
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
    </div>
    <!-- 表单 -->
    <el-form
      ref="formCom"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="form"
      key="loginKey"
      v-if="!isMsgLogin"
    >
      <div class="form-item">
        <div class="input">
          <el-form-item prop="account">
            <i class="iconfont icon-user"></i>
            <el-input
              v-model="form.account"
              type="text"
              placeholder="请输入用户名"
              autocomplete="off"
            />
          </el-form-item>
        </div>
      </div>
      <div class="form-item">
        <div class="input">
          <el-form-item prop="password">
            <i class="iconfont icon-lock"></i>
            <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
              autocomplete="off"
            />
          </el-form-item>
        </div>
        <div class="form-item" style="color: red">
          测试专用账号
          为保障您的个人信息安全请勿向平台录入任何个人敏感信息（如手机号、身份证号等）！
        </div>
      </div>
      <div class="form-item">
        <div class="agree">
          <el-form-item prop="isAgree">
            <i
              class="iconfont icon-warning"
              v-if="!form.isAgree"
              style="color: red; position: absolute; top: 30px; left: -4px"
            />
            <el-checkbox v-model="form.isAgree" name="isAgree" />
          </el-form-item>
          <div class="info">
            <span>我已同意</span>
            <a href="javascript:;">《隐私条款》</a>
            <span>和</span>
            <a href="javascript:;">《服务条款》</a>
          </div>
        </div>
      </div>
      <a @click="login(formCom)" href="javascript:;" class="btn">登录</a>
    </el-form>
    <el-form
      ref="formCom"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="form"
      key="phoneKey"
      v-else
    >
      <div class="form-item">
        <div class="input">
          <el-form-item prop="mobile">
            <i class="iconfont icon-user"></i>
            <el-input
              v-model="form.mobile"
              type="text"
              placeholder="请输入手机号"
              autocomplete="off"
            />
          </el-form-item>
        </div>
      </div>
      <div class="form-item">
        <div class="input">
          <el-form-item prop="code">
            <i class="iconfont icon-code"></i>
            <el-input
              v-model="form.code"
              type="text"
              placeholder="请输入验证码"
              autocomplete="off"
            />
          </el-form-item>
          <span @click="send(formCom)" class="code">
            {{ time === 0 ? '发送验证码' : `${time}秒后发送` }}
          </span>
        </div>
      </div>
      <div class="form-item">
        <div class="agree">
          <el-form-item prop="isAgree">
            <i
              class="iconfont icon-warning"
              v-if="!form.isAgree"
              style="color: red; position: absolute; top: 30px; left: -4px"
            />
            <el-checkbox v-model="form.isAgree" name="isAgree" />
          </el-form-item>
          <div class="info">
            <span>我已同意</span>
            <a href="javascript:;">《隐私条款》</a>
            <span>和</span>
            <a href="javascript:;">《服务条款》</a>
          </div>
        </div>
      </div>
      <a @click="login(formCom)" href="javascript:;" class="btn">登录</a>
    </el-form>
    <!-- 第三方qq登录 -->
    <div class="action">
      <a
        href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback"
      >
        <img
          src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png"
          alt=""
        />
      </a>
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>
<script>
import { reactive, ref, watch } from 'vue'
import {
  account,
  password,
  mobile,
  code,
  isAgree
} from '@/utils/vee-validate-schema'
import { useIntervalFn } from '@vueuse/core'
import { message } from '../../../components/library/message'
import {
  userAccountLogin,
  userMobileLogin,
  userMobileLoginMsg
} from '@/api/user'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
export default {
  name: 'LoginForm',
  setup() {
    // 切换短信登录
    const isMsgLogin = ref(false)
    // 表单数据对象
    const form = reactive({
      isAgree: true,
      account: 'demo123',
      password: '123456',
      mobile: null,
      code: null
    })
    const rules = reactive({
      account: [
        {
          validator: account,
          trigger: 'blur'
        }
      ],
      password: [
        {
          validator: password,
          trigger: 'blur'
        }
      ],
      mobile: [
        {
          validator: mobile,
          trigger: 'blur'
        }
      ],
      code: [
        {
          validator: code,
          trigger: 'blur'
        }
      ],
      isAgree: [
        {
          validator: isAgree,
          trigger: 'change'
        }
      ]
    })
    // 监听isMsgLogin重置表单（数据+清除校验结果）
    const formCom = ref(null)
    watch(isMsgLogin, () => {
      // 重置数据
      form.isAgree = true
      form.account = null
      form.password = null
      form.mobile = null
      form.code = null
      // 如果是没有销毁Field组件，之前的校验结果是不会清除  例如：v-show切换的
      // Form组件提供了一个 resetForm 函数清除校验结果
      formCom.value.resetFields()
    })

    const loginType = () => {
      isMsgLogin.value = !isMsgLogin.value
      formCom.value.resetFields()
    }
    /**
     *  登录逻辑
     */
    // 使用store
    const store = useStore()
    // 使用router
    const router = useRouter()
    // 使用route
    const route = useRoute()
    /**
     * 整个登录逻辑
     */
    // 登录提交
    const login = async (formEl) => {
      // Form组件提供了一个 validate 函数作为整体表单校验，当是返回的是一个promise
      const valid = formEl.validate()
      if (valid) {
        // 发送请求
        let data = null
        try {
          if (!isMsgLogin.value) {
            // 账号密码登陆
            data = await userAccountLogin(form)
          } else {
            // 短信登录
            // 1. 定义两个API  短信登录，获取短信验证码
            // 2. 实现发送短信验证码发送功能
            // 3. 完成手机号短信验证码登录逻辑
            data = await userMobileLogin(form)
          }
        } catch (e) {
          message({
            type: 'error',
            message: e.response.data.message || '登录失败'
          })
        }
        // 成功
        // 1.存储信息
        const { id, avatar, nickname, account, mobile, token } = data.result
        store.commit('user/setUser', {
          id,
          avatar,
          nickname,
          account,
          mobile,
          token
        })
        // 合并购物车
        store.dispatch('cart/mergeLocalCart')
        // 2.提示
        message({ type: 'success', message: '登录成功' })
        // 3.跳转
        router.push(route.query.redirectUrl || '/')
      }
    }
    /**
     *  短信发送逻辑
     */
    // pause暂停，resume开始
    // useIntervalFn(回调函数，执行间隔，是否立即开启)
    const time = ref(0)
    const { pause, resume } = useIntervalFn(
      () => {
        time.value--
        if (time.value <= 0) {
          pause()
        }
      },
      1000,
      { immediate: false }
    )
    // 发送短信
    const send = async (formEl) => {
      const valid = formEl.validate()
      if (valid) {
        if (form.mobile) {
          // 通过倒计时没有结束直接退出
          if (time.value !== 0) return
          try {
            // 发送短信验证码
            await userMobileLoginMsg(form.mobile)
            // 发送成功后提示
            message({ type: 'success', message: '发送成功' })
            // 重置倒计时秒数
            time.value = 60 * 2
            // 启动定时器
            resume()
          } catch (e) {
            message({
              type: 'error',
              message: e.response.data.message || '登录失败'
            })
          }
        }
      }
    }
    return {
      isMsgLogin,
      rules,
      formCom,
      loginType,
      form,
      login,
      send,
      time
    }
  }
}
</script>
<style scoped lang="less">
// 账号容器
:deep(.el-form-item__content) {
  margin-left: 0 !important;
}
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: @color;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          z-index: 9999;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        .el-input {
          // padding-left: 24px;
          // border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: @priceColor;
          }
          // &.active,
          // &:focus {
          //   border-color: @color;
          // }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }

    .agree {
      display: flex;
      align-items: center;
      margin-bottom: -20px;
      margin-top: -10px;
      :deep(.el-form-item__error) {
        writing-mode: vertical-lr !important;
        margin-top: 5px;
        margin-left: 11px;
      }
      .el-checkbox {
        position: relative;
        top: 8.5px;
        left: 2px;
      }
      .info {
        margin-left: 5px;
      }
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @color;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>
